﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using SongSharp.Domain.Data;

namespace SongSharp.Domain.Objects
{
    [Serializable()]
    public class Track
    {
        private static DataManager DataContext = DataManager.Instance;
        private TrackStatistic m_trackStatistic;

        public string Uid { get; set; }
        public string Url { get; set; }

        [XmlIgnore]
        public bool IsTransient { get; set; }

        [XmlIgnore]
        public TrackStatistic Statistic
        {
            get
            {
                if (m_trackStatistic == null)
                    m_trackStatistic = DataContext.GetTrackStatisticByTrackID(this.Uid);
                return m_trackStatistic;
            }

        }

        public Track()
        {
            IsTransient = false;
        }
        public Track(string url)
        {
            Uid = Guid.NewGuid().ToString();
            Url = url;
            IsTransient = false;
        }

        public Track(string url, bool isTransient)
        {
            Url = url;
            IsTransient = isTransient;
        }

        public override string ToString()
        {
            return Url;
        }

        public static List<Track> GetAll()
        {
            return DataContext.Tracks;
        }

        public static Track GetByID(string trackID)
        {
            return DataContext.Tracks
                .Where(t => t.Uid == trackID)
                .FirstOrDefault();
        }

        public static void SaveTracks(List<Track> tracks)
        {
            foreach (Track t in tracks)
            {
                t.Statistic.DateAdded = DateTime.Now;
                t.SaveStatistic();
            }

            DataContext.AddTracks(tracks);
        }

        public void SaveStatistic()
        {
            DataContext.UpdateTrackStatistic(this.Uid, this.Statistic);
        }
    }
}
